package com.chuangjian.hire.users.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.kisso.SSOCache;
import com.baomidou.kisso.SSOConfig;
import com.baomidou.kisso.security.token.SSOToken;
import com.chuangjian.hire.users.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class SSOCacheImpl implements SSOCache {
    @Resource
    RedisTemplate<String, String> redisTemplate;

    @Override
    public SSOToken get(String key, int expires) {
        String tokenStr = redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(tokenStr)) {
            SSOToken ssoToken = JSON.parseObject(tokenStr, SSOToken.class);
            redisTemplate.opsForValue().set(key, tokenStr, expires, TimeUnit.MINUTES);
            log.info("设置cookies key:{} value:{}", key, tokenStr);
            return ssoToken;
        }
        return null;
    }

    @Override
    public boolean set(String key, SSOToken ssoToken, int expires) {
        String tokenStr = JSON.toJSONString(ssoToken);
        log.info("设置cookies key:{} value:{}", key, tokenStr);
        redisTemplate.opsForValue().set(key, tokenStr, expires, TimeUnit.MINUTES);
        return true;
    }

    public boolean refreshCache(UserDTO users) {
        String key = SSOConfig.toCacheKey(users.getPhone());
        SSOToken ssoToken = get(key, SSOConfig.getInstance().getCacheExpires());
        if (ssoToken != null) {
            ssoToken.setData(users);
            ssoToken.setJwtBuilder(null);
            set(key, ssoToken, SSOConfig.getInstance().getCacheExpires());
        }
        return true;
    }


    @Override
    public boolean delete(String key) {
        return redisTemplate.delete(key);
    }
}
